package com.jack.helloworld.activity;

import android.os.Bundle;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

import com.jack.helloworld.R;
import com.jack.helloworld.adapter.GalleryAdapter;

import java.util.ArrayList;
import java.util.List;

import androidx.appcompat.app.AppCompatActivity;

public class GalleryActivity extends AppCompatActivity implements ViewSwitcher.ViewFactory, AdapterView.OnItemSelectedListener {

    List<Integer> listId;
    Gallery gallery;
    GalleryAdapter galleryAdapter;
    ImageSwitcher imageSwitcher;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gallery);

        initView();
        initData();
    }

    private void initView() {
        gallery = (Gallery) findViewById(R.id.gallery);
        imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);
    }

    private void initData() {
        listId = new ArrayList<Integer>();
        listId.add(R.mipmap.img1);
        listId.add(R.mipmap.img2);
        listId.add(R.mipmap.img3);
        listId.add(R.mipmap.img4);
        listId.add(R.mipmap.img5);

        galleryAdapter = new GalleryAdapter(listId, this);

        gallery.setAdapter(galleryAdapter);
        gallery.setOnItemSelectedListener(this);

        imageSwitcher.setFactory(this);
        imageSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_in));
        imageSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, android.R.anim.fade_out));
    }

    @Override
    public View makeView() {
        ImageView imageView = new ImageView(this);
        imageView.setScaleType(ImageView.ScaleType.CENTER);

        return imageView;
    }


    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        imageSwitcher.setBackgroundResource(listId.get(position % listId.size()));
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
}
